package com.example.tobebigfe.jsbridge

import android.content.Intent
import android.webkit.WebView
import com.example.tobebigfe.web.WebManager
import org.json.JSONObject

class JSBridgeNavigation(val activity: WebActivity, webView: WebView) : BridgeModuleBase(webView) {

    override fun callFunc(func: String, callbackId: String, arg: JSONObject) {
        when (func) {
            "open" -> open(callbackId, arg)
            "close" -> close(callbackId, arg)
            "getParams" -> getParams(callbackId, arg)
        }
    }

    private fun open(callbackId: String, arg: JSONObject) {
        val intent = Intent(activity, WebActivity::class.java)

        // 如果前端传递了id参数，说明使用项目名跳转方式
        if (arg.has("id")) {
            val id = arg.getString("id")
            val page = arg.getString("page")
            val url = WebManager.getWebUrl(id, page)
            intent.putExtra("url", url)
            intent.putExtra("project", id)
        }
        // 否则有url参数的情况
        else if (arg.has("url")) {
            intent.putExtra("url", arg.getString("url"))
        }

        if (arg.has("params")) {
            val params = arg.get("params") as JSONObject?
            params?.let {
                intent.putExtra("params", it.toString())
            }
        }

        activity.startActivity(intent)
    }

    private fun close(callbackId: String, arg: JSONObject) {
        activity.finish()
    }

    private fun getParams(callbackId: String, arg: JSONObject) {
        val paramsStr = activity.intent.getStringExtra("params")
        if (paramsStr == null) {
            callback(callbackId, JSONObject())
            return
        }
        paramsStr?.let {
            val params = JSONObject(it)
            callback(callbackId, params)
        }
    }

}